package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.server.PathParam;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.system.domain.HatchetAdministrativeDivision;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetIssBank;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetMoneyChange;
import com.ruoyi.system.domain.HatchetOrderPayment;
import com.ruoyi.system.service.IHatchetAdministrativeDivisionService;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetIssBankService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetMoneyChangeService;
import com.ruoyi.system.service.IHatchetOrderPaymentService;
import com.ruoyi.system.service.IHatchetSystemUserService;
import com.ruoyi.system.service.ISysDictDataService;

/**
 * 代理商 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-02-15
 */
@Controller
@RequestMapping("/system/hatchetAgent")
public class HatchetAgentController extends BaseController {
	private String prefix = "system/hatchetAgent";

	@Autowired
	private IHatchetAgentService hatchetAgentService;
	@Autowired
	private IHatchetIssBankService hatchetIssBankService;
	@Autowired
	private IHatchetSystemUserService hatchetSystemUserService;
	@Autowired
	private IHatchetAdministrativeDivisionService hatchetAdministrativeDivisionService;
	@Autowired
	private ISysDictDataService dictDataService;
	@Autowired
	private IHatchetMoneyChangeService moneyChangeService;
	@Autowired
	private IHatchetMerchantService hatchetMerchantService;
	@Autowired
	private IHatchetMerchantService merchantService;
	@Autowired
	private IHatchetOrderPaymentService orderPaymentService;

	@RequiresPermissions("system:hatchetAgent:view")
	@GetMapping("/{status}")
	public String hatchetAgent(@PathVariable("status") Integer status) {
		// 映射到静态页面地址
		if (status == 1) {
			return prefix + "/hatchetAgent";
		}
		// 代理商专属列表页面
		if (status == 2) {
			return prefix + "/hatchetAgentForDLS";
			// 商务中心排名
		} else if (status == 3) {
			return prefix + "/hatchetAgent2";
		}
		return null;
	}

	/**
	 * 查询代理商列表
	 */
	@RequiresPermissions("system:hatchetAgent:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(HatchetAgent hatchetAgent) {
		if (StringUtils.isNotEmpty(hatchetAgent.getParentId())) {
			// 通过搜索上级代理名称来查询上级代理商的id
			HatchetAgent paramAgent = new HatchetAgent();
			paramAgent.setAgentName(hatchetAgent.getParentId());
			List<HatchetAgent> agentList = hatchetAgentService.selectHatchetAgentList(paramAgent);
			if (agentList != null && agentList.size() > 0) {
				// 设置上级代理商id
				hatchetAgent.setParentId(agentList.get(0).getID());
			} else {
				return getDataTable(new ArrayList<>());
			}
		}
		startPage();
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentList(hatchetAgent);
		for (HatchetAgent hatchetAgent2 : list) {
			if (hatchetAgent2.getParentId() != null) {
				HatchetAgent hatchetAgent3 = hatchetAgentService.selectHatchetAgentById(hatchetAgent2.getParentId());
				hatchetAgent2.setParentId(hatchetAgent3.getAgentName());
			}
		}
		return getDataTable(list);
	}

	/**
	 * 导出代理商列表
	 */
	@RequiresPermissions("system:hatchetAgent:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(HatchetAgent hatchetAgent) {
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentList(hatchetAgent);
		ExcelUtil<HatchetAgent> util = new ExcelUtil<HatchetAgent>(HatchetAgent.class);
		return util.exportExcel(list, "hatchetAgent");
	}

	/**
	 * 新增代理商
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存代理商
	 */
	@RequiresPermissions("system:hatchetAgent:add")
	@Log(title = "代理商", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(HatchetAgent hatchetAgent) {
		return toAjax(hatchetAgentService.insertHatchetAgent(hatchetAgent));
	}

	/**
	 * 修改代理商
	 */
	@GetMapping("/edit/{iD}")
	public String edit(@PathVariable("iD") String iD, ModelMap mmap) {
		HatchetAgent hatchetAgent = hatchetAgentService.selectHatchetAgentById(iD);
		mmap.put("hatchetAgent", hatchetAgent);
		return prefix + "/edit";
	}

	/**
	 * 代理商详情
	 */
	@RequiresPermissions("system:hatchetAgent:detail")
	@GetMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, ModelMap mmap) {
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(id);
		if (agent.getIssbankId() != null) {
			String bankName = hatchetIssBankService.selectHatchetIssBankById(agent.getIssbankId()).getBankName();
			agent.setIssbankId(bankName);
		}
		if (agent.getCreateUserId() != null) {
			String agentNo = hatchetSystemUserService.selectHatchetSystemUserById(agent.getCreateUserId())
					.getLoginName();
			agent.setCreateUserId(agentNo);
		}
		// 获取银行省市区
		String province = null;
		String city = null;
		String area = null;
		if (agent.getBankProvinceId() != null) {
			province = hatchetAdministrativeDivisionService
					.selectHatchetAdministrativeDivisionById(agent.getBankProvinceId()).getDivisionName();
		}
		if (agent.getBankCityId() != null) {
			city = hatchetAdministrativeDivisionService.selectHatchetAdministrativeDivisionById(agent.getBankCityId())
					.getDivisionName();
		}
		if (agent.getBankAreaId() != null) {
			area = hatchetAdministrativeDivisionService.selectHatchetAdministrativeDivisionById(agent.getBankAreaId())
					.getDivisionName();
		}
		agent.setADDRESS(province + city + area);
		mmap.put("hatchetAgent", agent);
		return prefix + "/detail";
	}

	/**
	 * 修改保存代理商
	 */
	@RequiresPermissions("system:hatchetAgent:edit")
	@Log(title = "代理商", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(HatchetAgent hatchetAgent) {
		return toAjax(hatchetAgentService.updateHatchetAgent(hatchetAgent));
	}

	// 代理商操作部分
	/**
	 * 代理商查询代理商列表
	 */
	@RequiresPermissions("system:hatchetAgent:list")
	@PostMapping("/ForDLSlist")
	@ResponseBody
	public TableDataInfo forDLSlist(HatchetAgent hatchetAgent) {
		// 查出当前登陆的代理商信息
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentByNo(getLoginName());
		String departmentCode = StringUtils.likeDepartmentCode(agent.getDepartmentCode());
		hatchetAgent.setDepartmentCode(departmentCode);
		hatchetAgent.setID(agent.getID());
		// 根据parentId传的搜索条件来查询
		String parentId = null;
		if (StringUtils.isNotEmpty(hatchetAgent.getParentId())) {
			HatchetAgent paramAgent = new HatchetAgent();
			paramAgent.setAgentName(hatchetAgent.getParentId());
			// 通过搜索上级代理的名称来查询上级代理商的id
			List<HatchetAgent> selectHatchetAgentByaction = hatchetAgentService.selectHatchetAgentByaction(paramAgent);
			if (selectHatchetAgentByaction != null && selectHatchetAgentByaction.size() > 0) {
				parentId = selectHatchetAgentByaction.get(0).getID();
			}
		}
		if (StringUtils.isNotEmpty(parentId)) {
			hatchetAgent.setParentId(parentId);
		}
		startPage();
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentTree(hatchetAgent);
		for (HatchetAgent hatchetAgent2 : list) {
			if (hatchetAgent2.getParentId() != null) {
				HatchetAgent hatchetAgent3 = hatchetAgentService.selectHatchetAgentById(hatchetAgent2.getParentId());
				hatchetAgent2.setParentId(hatchetAgent3.getAgentName());
			}
			if (StringUtils.isNotEmpty(hatchetAgent2.getIdCardNo())) {
				hatchetAgent2.setIdCardNo(StringUtils.idCardNoString(hatchetAgent2.getIdCardNo(),4));
			}
		}
		return getDataTable(list);
	}

	/**
	 * 代理商基本信息
	 */
	@RequiresPermissions("system:hatchetAgent:view")
	@GetMapping("/info")
	public String info(ModelMap mmap) {
		String loginName = getLoginName();
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentByNo(loginName);
		if (agent.getIssbankId() != null) {
			String bankName = hatchetIssBankService.selectHatchetIssBankById(agent.getIssbankId()).getBankName();
			agent.setIssbankId(bankName);
		}
		if (agent.getCreateUserId() != null) {
			String agentNo = hatchetSystemUserService.selectHatchetSystemUserById(agent.getCreateUserId())
					.getLoginName();
			agent.setCreateUserId(agentNo);
		}
		// 获取银行省市区
		String province = null;
		String city = null;
		String area = null;
		if (agent.getBankProvinceId() != null) {
			province = hatchetAdministrativeDivisionService
					.selectHatchetAdministrativeDivisionById(agent.getBankProvinceId()).getDivisionName();
		}
		if (agent.getBankCityId() != null) {
			city = hatchetAdministrativeDivisionService.selectHatchetAdministrativeDivisionById(agent.getBankCityId())
					.getDivisionName();
		}
		if (agent.getBankAreaId() != null) {
			area = hatchetAdministrativeDivisionService.selectHatchetAdministrativeDivisionById(agent.getBankAreaId())
					.getDivisionName();
		}
		// 设置银行地址
		agent.setADDRESS(province + city + area);
		/*
		 * private BigDecimal sumMoney;//总收益 private BigDecimal dayMoney;//当天收益 private
		 * Long merchantCount;//普通用户总数 private Long activMerchantCount;//总激活用户数 private
		 * Long dayActivMerchantCount;//当日激活用户数
		 */
		// 设置总收益
		agent.setSumMoney(moneyChangeService.selectSumFenRenChangeByUserId(loginName));// 总收益
		// 查询当天收益
		HatchetMoneyChange hatchetMoneyChange = new HatchetMoneyChange();
		hatchetMoneyChange.setUserId(loginName);
		Map<String, Object> params = new HashMap<>();
		params.put("beginTime", DateUtils.getNextDateStr(0).concat(" 00:00:00"));// 设置当天起始查询时间
		params.put("endTime", DateUtils.getNextDateStr(0).concat(" 23:59:59"));// 当天截止时间
		hatchetMoneyChange.setParams(params);
		List<HatchetMoneyChange> moneyChanges = moneyChangeService.selectFenRenChangeListByDay(hatchetMoneyChange);
		if (moneyChanges != null && moneyChanges.size() > 0) {
			agent.setDayMoney(moneyChanges.get(0).getTrxAmt());
		} else {
			agent.setDayMoney(new BigDecimal("0.00"));
		}
		HatchetMerchant hatchetMerchant = new HatchetMerchant();
		hatchetMerchant.setDepartmentCode(StringUtils.likeDepartmentCode(agent.getDepartmentCode()));
		// 设置普通用户总数
		Long merchantCountForDLS = hatchetMerchantService.selectHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setMerchantCount(merchantCountForDLS);
		// 设置已认证用户
		hatchetMerchant.setIsActive("01");
		Long activMerchantCountForDLS = hatchetMerchantService.selectActivHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setActivMerchantCount(activMerchantCountForDLS);
		hatchetMerchant.setIsActive("03");
		Long bindCount = hatchetMerchantService.selectActivHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setBindCount(bindCount + "");
		mmap.put("hatchetAgent", agent);
		return prefix + "/info";
	}

	/**
	 * 跳转代理商查看关系页面
	 * 
	 * @param 查看的代理商id
	 * @param mmap
	 * @return
	 */
	@RequiresPermissions("system:hatchetAgent:detail")
	@GetMapping("/detailForDLS/{id}")
	public String toShowPage(@PathVariable("id") String id, ModelMap mmap) {
		HatchetAgent agent = new HatchetAgent();
		agent.setID(id);
		mmap.put("agent", agent);
		return prefix + "/detailForDLS";
	}

	/**
	 * 代理商查看代理商关系
	 * 
	 * @param 查看的代理商id
	 * @param mmap
	 * @return
	 */
	@RequiresPermissions("system:hatchetAgent:view")
	@GetMapping("/showRelation")
	@ResponseBody
	public List<HatchetAgent> showRelation(String id) {
		// 获得登陆代理商用户id
		String loginNo = getLoginName();
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(id);
		// 查询代理商的总用户数量、激活用户数量、经纪人数量、黄金会员数量
		HatchetMerchant hatchetMerchant = new HatchetMerchant();
		hatchetMerchant.setDepartmentCode(StringUtils.likeDepartmentCode(agent.getDepartmentCode()));
		// 设置普通用户总数
		Long merchantCountForDLS = hatchetMerchantService.selectHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setMerchantCount(merchantCountForDLS);
		// 设置认证用户
		hatchetMerchant.setIsActive("01");
		Long activMerchantCountForDLS = hatchetMerchantService.selectActivHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setActivMerchantCount(activMerchantCountForDLS);
		// 设置经纪人数量
		hatchetMerchant.setLEVEL("3");
		Long brokerCount = hatchetMerchantService.selectHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setBrokerCount(brokerCount);
		// 设置经理未激活数量
		hatchetMerchant.setLEVEL("2");
		//借用 isActive 字段 值是01表示未激活
		hatchetMerchant.setIsActive("01");
		Long goldCount = hatchetMerchantService.selectHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setGoldCount(goldCount);
		
		// 设置经理已激活数量
		hatchetMerchant.setLEVEL("2");
		//借用 isActive字段 值是02表示未激活
		hatchetMerchant.setIsActive("02");
		Long mangerCount = hatchetMerchantService.selectHatchetMerchantCountForDLS(hatchetMerchant);
		agent.setMangerCount(mangerCount);
		hatchetMerchant.setIsActive(null);//不用该条件了
		HatchetAgent parentAgent = hatchetAgentService.selectHatchetAgentByNo(loginNo);
		// 判断查询的代理商和父级代理商的关系
		List<HatchetAgent> agents = new ArrayList<HatchetAgent>();
		if (agent.getParentId().equals(parentAgent.getID())) {
			agents.add(agent);
			agents.add(parentAgent);
		} else {
			agents.add(agent);
			while (!agent.getParentId().equals(parentAgent.getID())) {
				agent = hatchetAgentService.selectHatchetAgentById(agent.getParentId());
				agents.add(agent);
				// 查询代理的父级代理和登陆的代理一致，就不再循环
			}
			agents.add(parentAgent);
		}
		for (HatchetAgent hatchetAgent : agents) {
			// 高级合伙人 不从字典表里面查
			if ("3".equals(hatchetAgent.getTYPE()) && "1".equals(hatchetAgent.getLEVEL())) {
				hatchetAgent.setTYPE("高级合伙人");
			} else {
				String type = dictDataService.selectDictLabel("agent_level", hatchetAgent.getTYPE());
				hatchetAgent.setTYPE(type);
			}
		}
		return agents;
	}

	/**
	 * 修改代理商状态--禁用/开启
	 */
	@RequiresPermissions("system:hatchetAgent:edit")
	@Log(title = "代理商", businessType = BusinessType.UPDATE)
	@PostMapping("/changeStatus")
	@ResponseBody
	public Map<String, Object> changeStatus(@PathParam("agentId") String agentId,
			@PathParam("logoText") String logoText) {
		Map<String, Object> map = new HashMap<>();
		try {
			map = hatchetAgentService.changeStatus(agentId, logoText);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "操作失败");
		}
		return map;
	}

	/**
	 * 添加下级代理商
	 */
	@GetMapping("/add/{iD}")
	public String add(@PathVariable("iD") String iD, ModelMap mmap) {
		HatchetAgent hatchetAgent = hatchetAgentService.selectHatchetAgentById(iD);
		mmap.put("hatchetAgent", hatchetAgent);
		return prefix + "/add";
	}

	/**
	 * 获取全部银行列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getIssBankAll", method = RequestMethod.POST)
	public List<HatchetIssBank> getIssbankAll() {
		HatchetIssBank hatchetIssBank = new HatchetIssBank();
		return hatchetIssBankService.selectHatchetIssBankList(hatchetIssBank);
	}

	/**
	 * 获得全部的省列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllProvince")
	public List<HatchetAdministrativeDivision> getAllProvince() {
		HatchetAdministrativeDivision division = new HatchetAdministrativeDivision();
		division.setParentId("0");
		return hatchetAdministrativeDivisionService.selectHatchetAdministrativeDivisionList(division);
	}

	/**
	 * 获取某个大区的的省列表
	 * 
	 * @param areaId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getHatchetAdministrativeDivisionsByChinaAreaId", method = RequestMethod.POST)
	public List<HatchetAdministrativeDivision> getHatchetAdministrativeDivisionsByChinaAreaId(
			@RequestParam Map<String, String> mapParam) {
		HatchetAdministrativeDivision division = new HatchetAdministrativeDivision();
		division.setParentId(mapParam.get("parentId"));
		division.setChinaRegionId(mapParam.get("chinaRegionId"));
		return hatchetAdministrativeDivisionService.selectHatchetAdministrativeDivisionList(division);
	}

	/**
	 * 添加下级代理商
	 * 
	 * @param hatchetAgent
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/savaOrUpdateAgent", method = RequestMethod.POST)
	public AjaxResult saveAgent(HatchetAgent hatchetAgent) {
		try {
			Map<String, Object> map = hatchetAgentService.addAgent(hatchetAgent);
			String status = map.get("status") + "";
			String msg = map.get("msg") + "";
			if ("SUCCESS".equals(status)) {
				return AjaxResult.success("添加成功");
			} else {
				return AjaxResult.error(msg);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询代理商列表
	 */
	@RequiresPermissions("system:hatchetAgent:list")
	@PostMapping("/getAgentAll")
	@ResponseBody
	public List<HatchetAgent> getAgentAll(HatchetAgent hatchetAgent) {
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentList(hatchetAgent);
		return list;
	}

	/**
	 * 代理商查询代理商列表
	 */
	@RequiresPermissions("system:hatchetAgent:list")
	@PostMapping("/getAgentAllForDLS")
	@ResponseBody
	public List<HatchetAgent> getAgentAllForDLS(HatchetAgent hatchetAgent) {
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentByNo(getLoginName());
		List<HatchetAgent> list = new ArrayList<>();
		if (StringUtils.isNotNull(agent)) {
			String departmentCode = StringUtils.likeDepartmentCode(agent.getDepartmentCode());
			hatchetAgent.setDepartmentCode(departmentCode);
			list = hatchetAgentService.selectHatchetAgentTree(hatchetAgent);
		} else {
			list = hatchetAgentService.selectHatchetAgentList(hatchetAgent);
		}
		return list;
	}

	/**
	 * 代理商查询自己直接下级代理商
	 */
	@RequiresPermissions("system:hatchetAgent:list")
	@PostMapping("/getAgentChild")
	@ResponseBody
	public List<HatchetAgent> getAgentChild(HatchetAgent hatchetAgent) {
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentByNo(getLoginName());
		hatchetAgent.setParentId(agent.getID());
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentList(hatchetAgent);
		return list;
	}

	/**
	 * 代理商查询自己所有下级代理商
	 */
	@RequiresPermissions("system:hatchetAgent:list")
	@PostMapping("/getAgentBydepartCode")
	@ResponseBody
	public List<HatchetAgent> getAgentBydepartCode(HatchetAgent hatchetAgent) {
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentByNo(getLoginName());
		hatchetAgent.setDepartmentCode(StringUtils.likeDepartmentCode(agent.getDepartmentCode()));
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentTree(hatchetAgent);
		return list;
	}

	/**
	 * 修改代理商余额状态 激活/冻结
	 */
	@RequiresPermissions("system:hatchetAgent:edit")
	@Log(title = "代理商", businessType = BusinessType.UPDATE)
	@PostMapping("/changeUploadContract")
	@ResponseBody
	public AjaxResult changeUploadContract(HatchetAgent hatchetAgent) {
		return toAjax(hatchetAgentService.updateHatchetAgent(hatchetAgent));
	}

	@PostMapping("/selectAgentMerCount")
	@ResponseBody
	public TableDataInfo selectAgentMerCount() {
		HatchetAgent paramAgent = new HatchetAgent();
		paramAgent.setTYPE("1");// 只查询普通代理商
		paramAgent.setEmployStatus("10A");
		startPage();
		List<HatchetAgent> selectHatchetAgentList = hatchetAgentService.selectHatchetAgentList(paramAgent);
		for (HatchetAgent hatchetAgent : selectHatchetAgentList) {
			// 查询代理商的经纪人账号
			HatchetMerchant paramMerchant = new HatchetMerchant();
			paramMerchant.setIdCardNumber(hatchetAgent.getIdCardNo());
			List<HatchetMerchant> merchantList = merchantService.selectHatchetMerchantList(paramMerchant);
			if (StringUtils.isNotEmpty(merchantList)) {
				HatchetMerchant agentJJR = merchantList.get(0);
				// 查询直推经纪人
				HatchetMerchant paramMerchant1 = new HatchetMerchant();
				paramMerchant1.setParentPhone(agentJJR.getPHONE());
				paramMerchant1.setAgentId(hatchetAgent.getID());
				paramMerchant1.setLEVEL("3");// 经纪人
				Map<String, Object> map = new HashMap<>();
				map.put("beginTime", "2019-04-03");
				map.put("endTime", DateUtils.getDate());
				paramMerchant1.setParams(map);
				List<HatchetMerchant> merchantJJRList = merchantService.selectHatchetMerchantList(paramMerchant1);
				if (StringUtils.isNotEmpty(merchantJJRList)) {
					int count = merchantJJRList.size();
					boolean isAgenJJR = false;// 经纪人是否 是该代理商自己的商户账号
					for (HatchetMerchant hatchetMerchant : merchantJJRList) {
						if (hatchetMerchant.getIdCardNumber().equals(hatchetAgent.getIdCardNo())) {
							isAgenJJR = true;
						}
					}
					if (isAgenJJR) {
						count = count - 1;
					}
					hatchetAgent.setSumMoney(new BigDecimal(count + ""));// 激活代理商数量
				} else {
					hatchetAgent.setSumMoney(new BigDecimal("0"));
				}
			} else {
				hatchetAgent.setSumMoney(new BigDecimal("0"));
			}
		}
		return getDataTable(selectHatchetAgentList);
	}

	/**
	 * 导出代直推经纪人表列表
	 */
	@PostMapping("/exportJJR")
	@ResponseBody
	public AjaxResult exportJJR() {
		HatchetAgent paramAgent = new HatchetAgent();
		paramAgent.setTYPE("1");// 只查询普通代理商
		paramAgent.setEmployStatus("10A");
		startPage();
		List<HatchetAgent> selectHatchetAgentList = hatchetAgentService.selectHatchetAgentList(paramAgent);
		for (HatchetAgent hatchetAgent : selectHatchetAgentList) {
			// 查询代理商的经纪人账号
			HatchetMerchant paramMerchant = new HatchetMerchant();
			paramMerchant.setIdCardNumber(hatchetAgent.getIdCardNo());
			List<HatchetMerchant> merchantList = merchantService.selectHatchetMerchantList(paramMerchant);
			if (StringUtils.isNotEmpty(merchantList)) {
				HatchetMerchant agentJJR = merchantList.get(0);
				// 查询直推经纪人
				HatchetMerchant paramMerchant1 = new HatchetMerchant();
				paramMerchant1.setParentPhone(agentJJR.getPHONE());
				paramMerchant1.setAgentId(hatchetAgent.getID());
				paramMerchant1.setLEVEL("3");// 经纪人
				Map<String, Object> map = new HashMap<>();
				map.put("beginTime", "2019-04-03");
				map.put("endTime", DateUtils.getDate());
				paramMerchant1.setParams(map);
				List<HatchetMerchant> merchantJJRList = merchantService.selectHatchetMerchantList(paramMerchant1);
				if (StringUtils.isNotEmpty(merchantJJRList)) {
					int count = merchantJJRList.size();
					boolean isAgenJJR = false;// 经纪人是否 是该代理商自己的商户账号
					for (HatchetMerchant hatchetMerchant : merchantJJRList) {
						if (hatchetMerchant.getIdCardNumber().equals(hatchetAgent.getIdCardNo())) {
							isAgenJJR = true;
						}
					}
					// 排除代理商自己的经纪人
					if (isAgenJJR) {
						count = count - 1;
					}
					hatchetAgent.setSumMoney(new BigDecimal(count + ""));// 激活代理商数量
				} else {
					hatchetAgent.setSumMoney(new BigDecimal("0"));
				}
			} else {
				hatchetAgent.setSumMoney(new BigDecimal("0"));
			}
		}
		ExcelUtil<HatchetAgent> util = new ExcelUtil<HatchetAgent>(HatchetAgent.class);
		return util.exportExcel(selectHatchetAgentList, "hatchetAgent");
	}

	/**
	 * 查询代理商交易排行榜
	 * 
	 */
	@PostMapping("/sortAgent")
	@ResponseBody
	public List<HatchetAgent> sortAgent(HatchetAgent hatchetAgent, @PathParam(value = "tradeType") String tradeType,
			@PathParam(value = "type") String type) {
		hatchetAgent.setTYPE(type);// 默认是联创交易排名
		hatchetAgent.setEmployStatus("10A");
		List<HatchetAgent> list = hatchetAgentService.selectHatchetAgentList(hatchetAgent);
		// 查询每个代理商的交易金额
		for (HatchetAgent hatchetAgent2 : list) {
			HatchetOrderPayment orderPayment = new HatchetOrderPayment();
			orderPayment.getParams().put("beginTime", hatchetAgent.getBeginTime());
			orderPayment.getParams().put("endTime", hatchetAgent.getEndTime());
			orderPayment.setSTATUS("10B");
			if ("All".equals(tradeType)) {
			} else {
				orderPayment.setTradeType(tradeType);
			}
			orderPayment.setDepartmentCode(StringUtils.likeDepartmentCode(hatchetAgent2.getDepartmentCode()));
			BigDecimal sumMoney = orderPaymentService.selectSumMoney(orderPayment);
			hatchetAgent2.setSumMoney(sumMoney);
		}
		Collections.sort(list);
		return list;
	}
	
	/**
	 * 对账销账
	 */
	/*@Log(title = "分润下发", businessType = BusinessType.DELETE)*/
	@PostMapping("/checkMoney")
	@ResponseBody
	@Transactional
	public Map<String, Object> checkMoney(String id) {
		Map<String, Object> requestmap = new HashMap<String, Object>();
		HatchetAgent agent = hatchetAgentService.selectHatchetAgentById(id);
		if (agent!= null) {
			//总分润
			BigDecimal sumFenrun = moneyChangeService.selectSumFenRenChangeByUserId(agent.getAgentNo());
			HatchetMoneyChange moneyChange1 = new HatchetMoneyChange();
			//提现中
			moneyChange1.setUserId(agent.getAgentNo());
			moneyChange1.setSTATUS("10B");
			BigDecimal tixian1 = moneyChangeService.selectTixianSumMoney(moneyChange1);
			if (tixian1 == null) {
				tixian1 = new BigDecimal("0");
			}
			//提现通过
			moneyChange1.setUserId(agent.getAgentNo());
			moneyChange1.setSTATUS("10C");
			BigDecimal tixian2 = moneyChangeService.selectTixianSumMoney(moneyChange1);
			if (tixian2 == null) {
				tixian2 = new BigDecimal("0");
			}
			
			BigDecimal ktMoney = sumFenrun.subtract(tixian1).subtract(tixian2);
			//修改用户余额
			agent.setTotalMoney(ktMoney);
			agent.setUpdateTime(new Date());
			int a =  hatchetAgentService.updateHatchetAgent(agent);
			if (a>0) {
				requestmap.put("status", "SUCCESS");
				requestmap.put("msg", "对账完成，请前往提现列表，重新审核");
				return requestmap;
			}else {
				requestmap.put("status", "FAIL");
				requestmap.put("msg", "对账失败，请联系技术！");
				return requestmap;
			}
		} else {
			requestmap.put("status", "FAIL");
			requestmap.put("msg", "代理商不存在");
			return requestmap;
		}
	}

	

}
